// userStores.ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import api from '@/util/service'
import { Phone } from '@element-plus/icons-vue';

export const useLoginStore = defineStore('useLoginStore', {
  state: () => ({
    id: "", //用户id
    username: "", //登录用户名
    phone: "", //登录用户手机号
    email: "", //登录用户邮箱
    imgUrl: "", //登录用户头像地址
    utypeid: "", //用户类型id
    menus: [], //用户菜单
    userToken: "",
    lid: "",//站点信息
    isLogin: false, //表示用户是否登录
  }),
  getters: {
    getId: (state) => state.id,
    getUserName: (state) => state.username,
    getPhone: (state) => state.phone,
    getEmail: (state) => state.email,
    getImgUrl: (state) => state.imgUrl,
    getToken: (state) => state.userToken,
    getUtypeid: (state) => state.utypeid,
    getMenus: (state) => state.menus || [],
    getLid: (state) => state.lid,
    isLoggedIn: (state) => state.isLogin // 重命名 getter
  },
  actions: {
    //修改用户的头像
    setImgUrl(imgUrl: string) {
      this.imgUrl = imgUrl;
    },
    async login(user: any) {
      try {
        const res = await api.post("/upuser/login", user);
        return res;
      } catch (error) {
        throw error;
      }
    },
    logout() {
      this.userToken = '';
      this.username = '';
      this.imgUrl = '';
      this.isLogin = false; 
    },
    
    setterUserDetail(user: any) {
      this.id = user.id;
      this.username = user.username;
      this.imgUrl = user.imgPath;
      this.userToken = user.userToken;
      this.phone = user.phone;
      this.email = user.email;
      this.menus = user.menus;
      this.utypeid = user.utypeid;
      this.lid = user.lid;
      this.isLogin = true; // 登录成功时显式设置 isLogin 为 true
    }
  },
  // 修改持久化配置
  persist: {
    key: 'user-store', 
    storage: sessionStorage, // 存储位置
    paths: ['id', 'username', 'imgUrl', 'userToken', 'isLogin', 'phone', 'email', 'menus','lid'] // 需要持久化的字段
  }
})